package com.chukun.concurrency.concurrencyCollections;

import com.chukun.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;
import java.util.concurrent.*;

/**
 * 适合读多写少的场景，里面写的操作，通过每次复制数组，来操作，
 * 所以，写操作对于大数据量比较费时。。。。
 */
@Slf4j
@ThreadSafe
public class CopyOnWriteArraySetOperator {


    //并发线程总数
    private static final int totalThreadCount=1000;

    //允许同时访问的总数
    private static final int allowThreadCount = 200;

    private static Set<Integer> set=new CopyOnWriteArraySet<>();

    public static void main(String[] args) {

        CountDownLatch countDownLatch = new CountDownLatch(totalThreadCount);
        Semaphore semaphore = new Semaphore(allowThreadCount);
        ExecutorService executorService = Executors.newCachedThreadPool();

        for(int i=0;i<totalThreadCount;i++){
            final int count=i;
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    add(count);
                    semaphore.release();
                }catch (Exception e){
                    log.error("error count add ",e);
                }
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        System.out.println("size: "+ set.size());
    }

    private static void add(int i){
        set.add(i);
    }
}
